from google.appengine.ext import blobstore
from google.appengine.ext import db
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.api import memcache

from utils import *
from datatypes import Asset
from CONFIG import *

import urllib2

"""
Handles requests for /asset. Gets the Asset from the Blobstore
(or memcache if the item is cached and caching is enabled).
"""
class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, resource):
        blob_info = None

        # Get the asset key
        resource = str(urllib2.unquote(resource))

        # Check if we should use memcache
        if GAPYCDN_CONFIG["memcache_on"]:
            # Check if the asset is in memcache
            blob_info = memcache.get(resource)
        
        # Have we got a blob?
        if blob_info == None:
            # Get from the blobstore
            blob_info = blobstore.BlobInfo.get(resource)
			
            # If memcache is enabled, cache the asset
            if GAPYCDN_CONFIG["memcache_on"]:
                memcache.add(resource, blob_info, GAPYCDN_CONFIG["memcache_timeout"])
        
        # Have we got a blob?
        if blob_info != None:
            # Send the blob
            self.send_blob(blob_info)
        else:
            # Return a 404 error
            self.error(404)

